﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Research.Kinect.Nui;

namespace BaffoHat.Wpf.Controls
{
    public class KinectSensor
    {
        #region Mebri privati
        //Variabile per la gestione del multithreading
        private static object sync = new object();
        //Variabile che mantiene l'instanza
        private static volatile KinectSensor instance;

        private Runtime nui;
        #endregion

        #region Costruttore
        /// <summary>
        /// Costruttore Privato
        /// </summary>
        private KinectSensor()
        {
            InizializeRuntime();
        }
        #endregion

        #region Proprietà
        /// <summary>
        /// Ottiene l'istanza come singleton
        /// </summary>
        public static KinectSensor Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (sync)
                    {
                        if (instance == null)
                            instance = new KinectSensor();
                    }
                }
                return instance;
            }
        }
        #endregion

        private void InizializeRuntime()
        {
            try
            {
                // Set up the Kinect
                nui = new Runtime();
                nui.Initialize(RuntimeOptions.UseSkeletalTracking | RuntimeOptions.UseColor);
                nui.VideoStream.Open(ImageStreamType.Video, 2, ImageResolution.Resolution640x480, ImageType.Color);
                nui.SkeletonEngine.TransformSmooth = true;
                var parameters = new TransformSmoothParameters
                {
                    Smoothing = 0.3f,
                    Correction = 0.0f,
                    Prediction = 0.0f,
                    JitterRadius = 1.0f,
                    MaxDeviationRadius = 0.5f
                };
                nui.SkeletonEngine.SmoothParameters = parameters;

            }
            catch (Exception)
            {
                // Failed to set up the Kinect switch to using mouse movement
                nui = null;
            }
        }

        public Runtime Runtime
        {
            get { return nui; }
        }

        public Boolean IsInizialized
        {
            get { return (nui != null); }
        }

        public void Uninitialize()
        {
            if (nui != null)
                nui.Uninitialize();
        }
    }
}
